package com.fdb.efp.basic.framework.excel;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import com.alibaba.excel.metadata.BaseRowModel;

 /**
  * 生成excel， fluent API
  * @param <T>
  * @author hengyh
  * @since 2019年3月15日 下午3:06:10
  * @version 1.0
  */
public class ExcelWriteFactory<T extends BaseRowModel> {
    /** 输出流 */
    private OutputStream outputStream;
    /** 要写入的Excel内容 */
    private List<T> content;
    /** 要写入的是哪一个sheet页 */
    private Integer sheetNo;
    /** 表头行数 */
    private Integer headLine;
    /** sheet页名称 */
    private String sheetName;
    /** 是否关闭输出流 */
    private Boolean finish;

    public ExcelWriteFactory(final Builder<T> builder) {
        this.outputStream = builder.outputStream;
        this.content = builder.content;
        this.sheetNo = builder.sheetNo;
        this.headLine = builder.headLine;
        this.sheetName = builder.sheetName;
        this.finish = builder.finish;
    }

    public void write() throws IOException {
        ExcelUtil.writeExcel(outputStream, content, sheetNo, headLine, sheetName, finish);
    }


    public static <T extends BaseRowModel> Builder<T> create(List<T> content) {
        return new Builder<T>().content(content);
    }

    public static class Builder<T extends BaseRowModel> {
        /** 输出流, 必输*/
        private OutputStream outputStream;
        /** 要写入的Excel内容，必输 */
        private List<T> content;
        /** 要写入的是哪一个sheet页，可选 */
        private Integer sheetNo = 1;
        /** 表头行数，可选(当没有模板的时候有用) */
        private Integer headLine = 1;
        /** sheet页名称，可选 */
        private String sheetName;
        /** 是否关闭输出流，可选 */
        private Boolean finish = true;

        public Builder<T> outputStream(OutputStream outputStream) {
            this.outputStream = outputStream;
            return this;
        }
        public Builder<T> content(List<T> content) {
            this.content = content;
            return this;
        }
        public Builder<T> sheetNo(Integer sheetNo) {
            this.sheetNo = sheetNo;
            return this;
        }
        public Builder<T> headLine(Integer headLine) {
            this.headLine = headLine;
            return this;
        }
        public Builder<T> sheetName(String sheetName) {
            this.sheetName = sheetName;
            return this;
        }
        public Builder<T> finish(Boolean finish) {
            this.finish = finish;
            return this;
        }
        public void write() throws IOException {
            build().write();
        } 

        public ExcelWriteFactory<T> build() {
            return new ExcelWriteFactory<T>(this);
        }
    }

}
